from datetime import timedelta

from aiogram_dialog import DialogManager
from sqlalchemy.ext.asyncio import AsyncSession

from src.application.order.service import OrderService
from src.application.user.service import UserService
from src.config import Settings
from src.infrastructure.date_helpers import get_date_time
from src.infrastructure.db.services.allowed_ips import get_allowed_ips


async def user_orders_getter(dialog_manager: DialogManager, **kwargs):
    user_id: int = dialog_manager.event.from_user.id
    order_service: OrderService = dialog_manager.middleware_data.get("order_service")
    orders_status: str = dialog_manager.dialog_data.get("orders_status")
    orders_type: str = dialog_manager.start_data.get("orders_type")

    orders = await order_service.get_orders(user_id, order_status=orders_status, order_type=orders_type)

    return {
        "user_orders": orders.orders,
    }


async def user_payments_getter(dialog_manager: DialogManager, **kwargs):
    user_service: UserService = dialog_manager.middleware_data.get("user_service")

    user_id: int = dialog_manager.event.from_user.id
    dialog_manager.dialog_data["user_id"] = user_id
    user = await user_service.get_user_by_tg_id(user_id, joined=True)
    user_payments = user.payments

    return {
        "user_payments": user_payments,
        "count": len(user_payments),
    }


async def user_info_getter(dialog_manager: DialogManager, **kwargs):
    user_id: int = dialog_manager.middleware_data["event_from_user"].id
    config: Settings = dialog_manager.middleware_data.get("config")
    user_service: UserService = dialog_manager.middleware_data.get("user_service")
    order_service: OrderService = dialog_manager.middleware_data.get("order_service")

    user = await user_service.get_user_by_tg_id(user_id)
    user_orders = await order_service.get_orders(tg_user_id=user_id)

    date_now = get_date_time()
    if user.test_proxy_acquired:
        test_proxy_available = user.test_proxy_acquired <= date_now - timedelta(hours=24)
    else:
        test_proxy_available = True

    return {
        "user_orders": user_orders.orders,
        "is_admin": user_id in config.tg_bot.admin_ids,
        "orders_count": user_orders.total,
        "user_id": user_id,
        "user_balance": user.balance,
        "user_email": user.email,
        "reg_date": user.was_registered,
        "test_proxy_available": test_proxy_available,
    }


async def user_ips_getter(db_session: AsyncSession, dialog_manager: DialogManager, **kwargs):
    user_id: int = dialog_manager.middleware_data.get("event_from_user").id
    allowed_ips = await get_allowed_ips(db_session, user_id)

    return {
        "allowed_ips": allowed_ips,
        "count": len(allowed_ips),
    }
